<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css">


  <meta name="keywords" content="class,kotlin,继承,">








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2">






<meta name="description" content="简介本篇博客主要是介绍Kotlin语法中的【类和继承】相关的知识，帮助各位更快的掌握Kotlin，如果有疏漏或者错误，请在留言中指正，谢谢。  系列汇总地址   类声明类Kotlin中使用关键词class 声明类和java中保持一致，代码如下： 123 class Demo&amp;#123; //class + 类名&amp;#125; 类的构成=class +类名+类头（可选）+类体（可选），如果没有类体，括">
<meta name="keywords" content="class,kotlin,继承">
<meta property="og:type" content="article">
<meta property="og:title" content="【kotlin从入门到深坑】之类和继承">
<meta property="og:url" content="http://guohaiyang.tk/post/e05a8e4d.html">
<meta property="og:site_name" content="Android探索之路">
<meta property="og:description" content="简介本篇博客主要是介绍Kotlin语法中的【类和继承】相关的知识，帮助各位更快的掌握Kotlin，如果有疏漏或者错误，请在留言中指正，谢谢。  系列汇总地址   类声明类Kotlin中使用关键词class 声明类和java中保持一致，代码如下： 123 class Demo&amp;#123; //class + 类名&amp;#125; 类的构成=class +类名+类头（可选）+类体（可选），如果没有类体，括">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-12-26T17:44:13.287Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【kotlin从入门到深坑】之类和继承">
<meta name="twitter:description" content="简介本篇博客主要是介绍Kotlin语法中的【类和继承】相关的知识，帮助各位更快的掌握Kotlin，如果有疏漏或者错误，请在留言中指正，谢谢。  系列汇总地址   类声明类Kotlin中使用关键词class 声明类和java中保持一致，代码如下： 123 class Demo&amp;#123; //class + 类名&amp;#125; 类的构成=class +类名+类头（可选）+类体（可选），如果没有类体，括">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"hide","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键词进行搜索","hits_empty":"找不到有关『${query}』的文章，是不是去火星了？","hits_stats":"呼哧呼哧~~ 总于找到${hits} 篇文章，花了 ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://guohaiyang.tk/post/e05a8e4d.html">





  <title>【kotlin从入门到深坑】之类和继承 | Android探索之路</title>
  














</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <!-- 添加github fork me -->
    <a href="https://github.com/guohaiyang1992" rel="external nofollow noopener noreferrer" target="_blank"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Android探索之路</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">吾将上下而求索</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br>
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://guohaiyang.tk/post/e05a8e4d.html">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="guohaiyang">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="http://avatar.csdn.net/E/A/A/1_guohaiyang1992.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Android探索之路">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">【kotlin从入门到深坑】之类和继承</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-05-26T14:05:00+08:00">
                2017-05-26
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/Kotlin/" itemprop="url" rel="index">
                    <span itemprop="name">Kotlin</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/post/e05a8e4d.html" class="leancloud_visitors" data-flag-title="【kotlin从入门到深坑】之类和继承">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读热度</span>
               
                 <span class="leancloud-visitors-count"></span> ℃
             </span>
          

          

          
            <br>
            <div class="post-wordcount">
              
                <!--
                  <span class="post-meta-divider">|</span>
                -->
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计</span>
                
                <span title="字数统计">
                  2,675 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长</span>
                
                <span title="阅读时长">
                  10 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a><strong>简介</strong></h2><p>本篇博客主要是介绍Kotlin语法中的【类和继承】相关的知识，帮助各位更快的掌握Kotlin，如果有疏漏或者错误，请在留言中指正，谢谢。 <a href="http://blog.csdn.net/guohaiyang1992/article/details/72615889" rel="external nofollow noopener noreferrer" target="_blank"> 系列汇总地址
</a></p>
<hr>
<h2 id="类"><a href="#类" class="headerlink" title="类"></a><strong>类</strong></h2><h3 id="声明类"><a href="#声明类" class="headerlink" title="声明类"></a><strong>声明类</strong></h3><p>Kotlin中使用关键词class 声明类和java中保持一致，代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"> class Demo&#123; //class + 类名</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>类的构成=class +类名+类头（可选）+类体（可选），如果没有类体，括号也可省略</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">class Demo //class + 类名</span><br></pre></td></tr></table></figure>
<h3 id="主构造函数"><a href="#主构造函数" class="headerlink" title="主构造函数"></a><strong>主构造函数</strong></h3><p>在Kotlin的类中可以有一个主构造函数和多个次构造函数。我们看看什么样的算主构造函数，例子如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"> class Demo()&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>看了例子估计心里开始有疑惑了，这和上面的例子有什么不同？？仔细一看还真有不同，多了”（）”，这就声明了一个无参的主构造函数，当然你也可以声明有参数的，如下</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">class Demo(name: String)&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>主构造函数只是类头的一部分，还有一个可选关键词– <strong>constructor</strong> ，当主构造函数想声明为非public<br>类型的时候，需要使用该关键词其他时候可以省略，例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"> class Demo private constructor(name: String)&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这种情况一般是在写单例的时候会用到。</p>
<p>构造函数都有了，我们可以愉快的做些初始化了，但是但是要注意， <strong>主构造函数内不能包含任何代码。</strong> 这个时候我们需要使用另一个关键词 <code>init</code><br>,使用 <code>init</code> 代码块进行初始化代码即可，如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"> class Demo private constructor(name: String) &#123;</span><br><span class="line">    init &#123;//init代码块</span><br><span class="line">        println(&quot;测试输出&quot;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面的代码中 <code>name</code> 可以直接使用在 <strong><code>init</code> 代码块内和类体内声明的属性初始化中使用 </strong> ，只有这两种情况，代码如下</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"> class Demo (name: String) &#123;</span><br><span class="line">    init &#123;</span><br><span class="line">        println(&quot;测试输出&quot;+name) //在此处使用可以</span><br><span class="line">    &#125;</span><br><span class="line">    var nameTest=name //此处给nameTest赋值可以，但不可以单独使用</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当然我们可以让上面的 <code>name</code> 有更多的用途怎么办呢？可以这样写：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">class Demo(var name: String) &#123; //此处加入 var关键词</span><br><span class="line">    init &#123;</span><br><span class="line">        println(&quot;测试输出&quot; + name)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    var nameTest = name</span><br><span class="line"></span><br><span class="line">    fun printTest() &#123; //方法内也可使用了</span><br><span class="line">        println(name)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>不仅可以使用 <code>var</code> 关键词，还可以使用val，具体的差别之前我们说过，再次不再赘述。<br>使用该关键词后，name就等同于是该类的成员变量，就等同于你直接声明在类中。<br>对于Kotlin来说还有个好用的地方，就是你声明的类中变量不需要写get/set方法，默认就会有，可以直接用。</p>
<h3 id="次构造函数"><a href="#次构造函数" class="headerlink" title="次构造函数"></a><strong>次构造函数</strong></h3><p>Kotlin中类也可以声明前缀有 constructor 的 <strong>次构造函数</strong> ,如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"> class Demo &#123; //有个默认的无参主构造函数</span><br><span class="line">  constructor()&#123;// 有个无参次构造函数</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>如果类有一个主构造函数，每个次构造函数需要委托给主构造函数， 可以直接委托或者通过别的次构造函数间接委托。委托到同一个类的另一个构造函数 用 this<br>关键字即可</strong> 。</p>
<p>下面根据主构造函数是否重写来分别讲解，先说未重写:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"> class A&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如何写它的次构造函数呢？</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">class A &#123;</span><br><span class="line">    init &#123;</span><br><span class="line">        println(&quot;--A主构造--&quot;)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    constructor(name: String) &#123; //此处屏蔽了 默认的主构造函数</span><br><span class="line">        println(&quot;--A次构造--&quot;)</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上面的写法会导致Kotlin的默认无参主构造函数不可调用, 也就导致 <code>constructor(name: String)：this()</code><br>失效，但我们上面说过必须要委托给主构造函数，这怎么办？其实Kotlin内部仍然会走默认的主构造函数，也就是说<br><strong>如果是默认主构造是可以省略不写的，有的时候是想写也没法写</strong> 。</p>
<p>得到上面的结论是源于一个测试，代码如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">var a = A(&quot;name&quot;); //此处已经无法调用无参的，也就是默认的主构造失效，内部使用this(） 也是不可以的</span><br></pre></td></tr></table></figure>
<p>后面的打印结果</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">--A主构造--   //仍然走了主构造函数，此时只有默认主构造函数</span><br><span class="line">--A次构造--   //然后再走次构造</span><br></pre></td></tr></table></figure>
<p>所以得到上面的结论，在此佐证。 <strong>后续用实际代码详解，此处挖坑</strong> 。</p>
<p>有的筒子可能就会想了，如果我们仍然想要一个无参数的构造函数怎么写？</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"> class A &#123;</span><br><span class="line">    init &#123;</span><br><span class="line">        println(&quot;--A主构造--&quot;)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    constructor(name: String) &#123;</span><br><span class="line">        println(&quot;--A次构造--&quot;)</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    constructor()&#123; //增加一个无参的次构造函数</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>还有另一个方式，就是重写主构造函数，这两种方法都类似<br>java中自己重写一个无参的构造函数，现在就是区分了主、次构造函数的重写。还需强调的是主构造如果重写了，次构造不允许再重写。下面写个重写主构造函数的，后面细说：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">class A() &#123; //重写此处</span><br><span class="line">    init &#123;</span><br><span class="line">        println(&quot;--A主构造--&quot;)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    constructor(name: String) : this() &#123;</span><br><span class="line">        println(&quot;--A次构造--&quot;)</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">//    constructor()&#123; //次构造不允许使用</span><br><span class="line">//        </span><br><span class="line">//    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>下面我们讲一下重写主构造函数的<br>如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">class Demo() &#123; //没参数的主构造函数</span><br><span class="line">    constructor(name: String) : this() &#123; //次构造函数委托给</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>此处就和默认的不一样了，这个地方需要使用this()，因为你重写了主构造函数。如果不重写是可以不写this（）</p>
<p>通过上方的各种对比和例子我们对类的构造函数有了大概的了解，我们为了方便理解在这里总结一波，还有不明白的多看看例子：</p>
<ul>
<li><p>类只有一个主构造函数，但可以有一个或多个次构造函数 </p>
</li>
<li><p>次构造函数需要委托给主构造函数，可以通过直接或者间接的方式 </p>
</li>
<li><p>在声明期间，以主构造函数为主，如果主构造函数 <strong>重写</strong> 了对应的构造方法，次构造函数不能用重复的出现对应的构造函数，上面有例子说明。 </p>
</li>
<li><p>在调用期间，以次构造函数为主，如果未重写主构造函数，默认会有一个无参的主构造函数，如果重写一个无参次构造函数，则可调用的只有次构造函数。 </p>
</li>
</ul>
<h3 id="创建类的实例"><a href="#创建类的实例" class="headerlink" title="创建类的实例"></a><strong>创建类的实例</strong></h3><p>要创建一个类的实例，我们就像普通函数一样调用构造函数：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"> val invoice = Invoice()</span><br><span class="line">val customer = Customer(&quot;Joe Smith&quot;)</span><br><span class="line">//注意 Kotlin 并没有 new 关键字。</span><br></pre></td></tr></table></figure>
<h2 id="继承"><a href="#继承" class="headerlink" title="继承"></a><strong>继承</strong></h2><p>在 Kotlin 中所有类都有一个共同的超类 Any，这对于没有超类型声明的类是默认超类：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">class Example // 从 Any 隐式继承</span><br></pre></td></tr></table></figure>
<p>Any 不是 java.lang.Object；尤其是，它除了 equals()、hashCode()和toString()外没有任何成员。<br>更多细节请查阅Java互操作性部分。</p>
<p>要声明一个显式的超类型，我们把类型放到类头的冒号之后：</p>
 <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">open class A(p: Int) //注意此处的 open 关键词</span><br><span class="line"></span><br><span class="line">class B(p: Int) : Base(p) //使用&quot; ：&quot;</span><br></pre></td></tr></table></figure>
<p><strong>对于继承的类来说，它仍需满足之前类中主次构造函数的规定，还需满足继承类委托给被继承类的主构造函数（保证对应类的init模块都能运行的关键），此处的被委托的主构造函数如果是无参构造函数，可以省略不写</strong></p>
<p>下面我们分两种类型去分别讲解，首先是未修改默认的主构造函数的情况：<br>我们先看一下被继承类：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">open  class BB &#123; //未重写默主构造</span><br><span class="line"></span><br><span class="line">    constructor(name: String) &#123;</span><br><span class="line">        println(name + &quot;---BB&quot;)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    constructor() &#123;</span><br><span class="line">        println(&quot;.....---BB&quot;)</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>继承类：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">class testA : BB &#123; //此处testA也没重写主构造</span><br><span class="line">    constructor(name: String) : super(name) &#123;//--    1)</span><br><span class="line">        println(&quot;A---&quot; + name)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    constructor() &#123;//--  2)</span><br><span class="line">        println(&quot;A---&quot; + &quot;ss&quot;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>位置1处的构造函数，因为未重写主构造，所以本类的委托完成，所以只需委托父类即可，即可满足上面说的要求。</p>
<p>位置2处的构造函数，因为未重写主构造，所以本类的委托完成，又因为默认是委托父类的无参主构造函数（系统默认的或者重写的都满足），所以满足上面说的要求。</p>
<p>我们做下改动，将B 改动如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">open class BB() &#123;//重写默认主构造</span><br><span class="line"></span><br><span class="line">    constructor(name: String):this() &#123; //手动委托主构造</span><br><span class="line">        println(name + &quot;---BB&quot;)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">//    constructor() &#123; //根据主次函数关系，此处无法存在</span><br><span class="line">//        println(&quot;.....---BB&quot;)</span><br><span class="line">//</span><br><span class="line">//    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这时候我们的继承类如何写呢？</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">class testA : BB &#123;</span><br><span class="line">    constructor(name: String) : super(name) &#123;</span><br><span class="line">        println(&quot;A---&quot; + name)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    constructor() &#123;</span><br><span class="line">        println(&quot;A---&quot; + &quot;ss&quot;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可以看到代码是没变化的，也就是说，只要是被继承类的主构造函数，是无参的，无论是默认还是重写都可以省略不写，当然也可以写上</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">class testA : BB &#123;</span><br><span class="line">    constructor(name: String) : super(name) &#123;//可以选择不同的父类的主构造函数进行委托</span><br><span class="line">        println(&quot;A---&quot; + name)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    constructor():super() &#123;//无参的委托</span><br><span class="line">        println(&quot;A---&quot; + &quot;ss&quot;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>下面我们将一下修改默认主构造函数的情况</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">class testB(name: String) : BB(name) &#123; //此处testB重写了默认主构造，所以此处B一定需要用主构造函数（直接或间接的）</span><br><span class="line">    init &#123;</span><br><span class="line">        println(name + &quot;99ss...---B&quot;)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    constructor(name: String, age: Int) : this(name) &#123;</span><br><span class="line">        println(name + &quot;...---B&quot;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>也可以这样写：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">class testB(name: String) : BB() &#123; //此处必须有&quot;（）&quot;</span><br><span class="line">    init &#123;</span><br><span class="line">        println(name + &quot;99ss...---B&quot;)</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    constructor(name: String, age: Int) : this(name) &#123;  //此处不能使用super了，不能重复委托父类，主构造函数已经委托过了</span><br><span class="line">        println(name + &quot;...---B&quot;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>下面我们总结一波：</p>
<ul>
<li><p>如果继承的类重写了默认主构造函数，此时必须用基类的主构造函数初始化（直接或间接） </p>
</li>
<li><p>如果继承的类没重写默认的主构造函数，此时可以使用super关键词初始化，我们也说过，未重写的的默认主构造函数，次构造函数都会委托给它，所以本类内也满足了委托条件，对于类外，也委托了被继承类的主构造方法，完成了两个类的条件 </p>
</li>
</ul>
<hr>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>至此已经学完了Kotlin的类和继承相关的知识，多回顾多思考，继续 <a href="http://blog.csdn.net/guohaiyang1992/article/details/72615889" rel="external nofollow noopener noreferrer" target="_blank"> 后续内容
</a> 。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/class/" <i="" class="fa fa-tag"> class</a>
          
            <a href="/tags/kotlin/" <i="" class="fa fa-tag"> kotlin</a>
          
            <a href="/tags/继承/" <i="" class="fa fa-tag"> 继承</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/post/74742d5b.html" rel="next" title="【kotlin从入门到深坑】之语句">
                <i class="fa fa-chevron-left"></i> 【kotlin从入门到深坑】之语句
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/post/cb6db1c3.html" rel="prev" title="【Kotlin从入门到深坑】之返回和跳转">
                【Kotlin从入门到深坑】之返回和跳转 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zMjczNS85Mjk2"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image" src="http://avatar.csdn.net/E/A/A/1_guohaiyang1992.jpg" alt="guohaiyang">
          <p class="site-author-name" itemprop="name">guohaiyang</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
           
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">31</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">10</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">71</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


        <!--外链播放器-->
        <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width="330" height="86" src="//music.163.com/outchain/player?type=2&id=504575633&auto=0&height=66"></iframe>

      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#简介"><span class="nav-number">1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#类"><span class="nav-number">2.</span> <span class="nav-text">类</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#声明类"><span class="nav-number">2.1.</span> <span class="nav-text">声明类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#主构造函数"><span class="nav-number">2.2.</span> <span class="nav-text">主构造函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#次构造函数"><span class="nav-number">2.3.</span> <span class="nav-text">次构造函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#创建类的实例"><span class="nav-number">2.4.</span> <span class="nav-text">创建类的实例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#继承"><span class="nav-number">3.</span> <span class="nav-text">继承</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">guohaiyang</span>
</div>
<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<!--<div class="powered-by"> -->
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  您是本站的第<span id="busuanzi_value_site_uv"></span>个访客，欢迎您的到来
</span>
<!--</div>-->

<!--屏蔽下方提示-->
<!--<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div> -->


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "db.json";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("h8Ih0Dm3ikBRV6HNGyvsiu8C-gzGzoHsz", "LWjl3Esuf1ArMkWbwcPbjGqV");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  

  

</body>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>
</html>

